package com.nowcoder.community.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.mapper.CommentMapper;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: community
 * @description:
 * @author: hmx
 * @create: 2021-12-19 18:34
 **/
@Service
public class CommentService implements CommunityConstant {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private DiscussPostService discussPostService;

    /**
     * 根据实体寻找评论
     * @param entityType
     * @param entityId
     * @param offset
     * @param limit
     * @return
     */
    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getStatus, 0);
        queryWrapper.eq(Comment::getEntityId, entityId);
        queryWrapper.eq(Comment::getEntityType, entityType);
        queryWrapper.orderByAsc(Comment::getCreateTime);
        queryWrapper.last(" limit " + offset + ", " + limit);
        return commentMapper.selectList(queryWrapper);
    }

    public int findCommentCount(int entityType, int entityId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getStatus, 0);
        queryWrapper.eq(Comment::getEntityType, entityType);
        queryWrapper.eq(Comment::getEntityId, entityId);
        return commentMapper.selectCount(queryWrapper);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(SensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insert(comment);

        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = findCommentCount(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }
        return rows;
    }

    public Comment findCommentById(Integer id) {
        return commentMapper.selectById(id);
    }
}
